<?php
namespace App\Models;
use DB;
use Cache;
/**
 * Role.php
 * @author LF
 * @Date 16/7/9 11:29
 * @copyright Copyright© 2016-2016 飞煌科技
 * All Rights Reserved.
 * Code is poetry, thus is life.
 * @author JeffMing
 */
class Role extends BaseModel{
    protected $table = 'role';
    const CACHE_TYPE = 'file';
    public function __construct()
    {
    }

    /***
     * @param array $where
     * @param string $fields
     * @param string $order
     * @param string $pageSize
     * @return mixed
     * 获取列表
     */
    public function getList(array $where = [], $fields = '*', $order = '', $pageSize = '')
    {
        if ($pageSize) {
            $roles = $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->paginate($pageSize);
        } else {
            $roles = $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->get();
        }
        return $roles;
    }

    /**
     * @param $id
     * 删除数据
     */
    public function del($id){
       DB::beginTransaction();
       $res = $this->_del(['id'=>$id]);
       if(!$res){
           DB::rollback();
           return $res;
       }
       $role_node = new RoleNode();
       $res = $role_node->delByRoleId($id);
       if(!$res){
           DB::rollback();
           return $res;
       }
       DB::commit();
       $this->delRoleCache($id);
       return $res;
    }

    /***
     * @param $data
     * 添加角色信息及角色对应的权限信息
     */
    public function add($data){
        $role['name'] = $data['name'];
        $role['status'] = $data['status'];
        DB::beginTransaction();
           $res = $this->_add($role);
        if(!$res){
            DB::rollback();
            return $res;
        }
        if(!empty($data['nodes'])){
            foreach($data['nodes'] as $key => $node){
                $role_node[$key]['rid'] = $res;
                $role_node[$key]['nid'] = $node;
            }
            $role_nodel_model = new RoleNode();
            $res = $role_nodel_model->batInsertData($role_node);
            if(!$res){
                DB::rollback();
                return false;
            }
        }
        DB::commit();
        return true;
    }

    /***
     * @param $where
     * 获取角色信息
     */
    public function getOne($where,$fields="*"){
        return $this->_getOne($where,$fields);
    }

    /***
     * @param $id     角色id
     * @param $where  查询条件
     */
    public function getEditNodes($id,$where){
       $node_model = new Node();
       $nodes =  $node_model->getAllData($where);//获取所有的节点
       $role_nodel_model = new RoleNode();
       $checked_nodes = $role_nodel_model->getDataByRoleId(['rid'=>$id]);
       if($checked_nodes){
           $checked_nodes = $checked_nodes->toArray();
           $nodes_id = array_column($checked_nodes,'nid');
           foreach($nodes as $key => $item){
               if(in_array($item['id'],$nodes_id)){
                   $nodes[$key]['is_checked'] = 1;
               }else{
                   $nodes[$key]['is_checked'] = 0;
               }
           }
       }
       return $nodes;
    }

    /**
     * @param $id
     * @param $data
     * @return bool|mixed
     * 更新角色
     */
    public function upRole($id,$data){
        $role['name'] = $data['name'];
        $role['status'] = $data['status'];
        DB::beginTransaction();
        $res = $this->_updata(['id'=>$id],$role);
        if(!$res){
            DB::rollback();
            return $res;
        }
        if(!empty($data['nodes'])){
            $role_node_model = new RoleNode();
            $checked_node = $role_node_model->getAll(['rid'=>$id]);
            if($checked_node){
                $checked_node = $checked_node->toArray();
                $node_ids = array_column($checked_node,'nid');
                $add_nids = array_diff($data['nodes'],$node_ids);
                $del_nids = array_diff($node_ids,$data['nodes']);
                if(!empty($del_nids)){
                   $res =  $role_node_model->del(['rid'=>$id,'nid'=>['in',$del_nids]]);
                   if(!$res){
                       DB::rollback();
                       return false;
                   }
                }
                $role_node = array();
                foreach($add_nids as $key => $node){
                    $role_node[$key]['rid'] = $id;
                    $role_node[$key]['nid'] = $node;
                }
                if(!empty($role_node)){
                    $res = $role_node_model->batInsertData($role_node);
                    if(!$res){
                        DB::rollback();
                        return false;
                    }
                }

            }
        }
        DB::commit();
        $this->updateRoleCache($id);
        return true;
    }

    /***
     * @param $role_id
     * 更新角色权限缓存数据
     */
    private function updateRoleCache($role_id){
        $cache_key = "power_".$role_id;
        //文件缓存
        if(self::CACHE_TYPE == 'file'){
            if(Cache::has($cache_key)){
                Cache::forget($cache_key);
                $admins_model = new Admins();
                $nodes = $admins_model->getUserPower($role_id);
                if(!empty($nodes)){
                    return Cache::forever($cache_key,$nodes);
                }
            }
        }else if(self::CACHE_TYPE == 'memcache'){
            //获取用户权限
            $cache = new MemcachedCached();
            $nodes = $cache->get($cache_key);
            if($nodes){
                $admins_model = new Admins();
                $nodes = $admins_model->getUserPower($role_id);
                if(!empty($nodes)){
                    return $cache->set($cache_key,$nodes);
                }
            }
        }
        return false;
    }

    /***
     * @param $role_id
     * 删除角色权限缓存数据
     */
    private function delRoleCache($role_id){
        $cache_key = "power_".$role_id;
        if(self::CACHE_TYPE == 'file'){
            if(Cache::has($cache_key)){
                return Cache::forget($cache_key);
            }
        }else if(self::CACHE_TYPE == 'memcache'){
            //获取用户权限
            $cache = new MemcachedCached();
            return $cache->delete($cache_key);
        }
        return false;
    }
}